package com.mall.order.server.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.mall.common.redis.service.RedisService;
import com.mall.common.security.utils.SecurityUtils;
import com.mall.order.common.dto.OrderAndSku;
import com.mall.order.common.dto.OrderRequest;
import com.mall.order.common.dto.Sku;
import com.mall.order.common.po.OmsOrder;
import com.mall.order.server.mapper.OrderMapper;
import com.mall.order.server.service.OrderService;
import com.mall.pay.server.config.AlipayTemplate;
import com.mall.pay.server.controller.AliPayController;
import com.mall.system.common.model.LoginUser;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;

@Service
public class MqConsumerService {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private OrderService orderService;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private AliPayController aliPayController;
    @Autowired
    @Qualifier("asyncOrderExecutor")
    private Executor asyncOrderExecutor;


    private static final String QUEUE_NAME = "order_queue_QF"; // 定义消息队列名称

    @RabbitListener(queuesToDeclare = @Queue(QUEUE_NAME))
    public void mqConsumer(OrderRequest orderRequest) {
        List<Sku> skuList = orderRequest.getSkuList();

        CompletableFuture.supplyAsync(() -> {
                    // 阶段1：LUA扣减库存
                    return orderService.reduceStocks(skuList);
                }, asyncOrderExecutor).thenApplyAsync(result -> {
                    if (result.getCode() != 200) {
                        throw new RuntimeException("!!抱歉,出错了:" + result.getMsg());
                    }
                    return skuList;
                }, asyncOrderExecutor).thenApplyAsync(validSkuList -> {
                    // 阶段2：计算总价
                    BigDecimal totalPrice = getTotalPrice(validSkuList,orderRequest.getOrderSn());
                    //获取用户信息
                    Long userId = SecurityUtils.getUserId();

                    OmsOrder order = new OmsOrder();//创建订单对象
                    order.setPayAmount(totalPrice);//设置总金额
                    order.setUserId(userId);//设置购买人ID
                    order.setPayStatus(1);//设置状态为待支付
                    order.setOrderSn(orderRequest.getOrderSn());
                    order.setCreateBy(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
                    return order;
                }).thenAcceptAsync(order -> {
                    // 阶段4：添加订单插入redis
                    redisService.setCacheObject("Plan_Order:"+order.getOrderSn(), JSONObject.toJSONString(order), 1L, TimeUnit.HOURS);
                }, asyncOrderExecutor)
                .exceptionally(ex -> {
                    // 异常处理
                    System.err.println("!!订单处理失败: " + ex.getMessage());
                    return null;
                });
        System.out.println("操作完成");
    }


    /**
     * 获取下单商品总价格
     *
     * @param skuList
     * @return
     */
    private BigDecimal getTotalPrice(List<Sku> skuList,String orderSn) {

        LoginUser loginUser = SecurityUtils.getLoginUser();

        ArrayList<OrderAndSku> orderAndSkus = new ArrayList<>();

        //查询redis 进行计算总价
        BigDecimal sum = skuList.stream().map(sku -> {
            BigDecimal cacheObject = redisService.getCacheObject("HotSku:" + sku.getProductId());
            OrderAndSku orderAndSku = new OrderAndSku();
            orderAndSku.setSkuPrice(cacheObject);
            orderAndSku.setPayStatus(1);//设为待支付
            orderAndSku.setUserId(SecurityUtils.getUserId());
            orderAndSkus.add(orderAndSku);
            return cacheObject.multiply(new BigDecimal(sku.getQuantity()));
        }).reduce(BigDecimal.ZERO, BigDecimal::add);

        // 添加订单中间表到redis 订单主键 skuID 用户ID 时间
        redisService.setCacheList("Plan_Order_Sku:"+orderSn,orderAndSkus);

        System.out.println("下单总价:" + sum);
        return sum;
    }
}
